package com.sun.dailyprj.pki;

import android.util.Base64;

import com.sun.dailyprj.util.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import sun.security.pkcs.PKCS7;
import sun.security.pkcs.ParsingException;
import sun.security.pkcs.SignerInfo;

public class PKiUtils {



    public static boolean signedDataVerify(byte[] signedData, String sha256){
        try {
            PKCS7 pkcs7 = new PKCS7(Base64.decode(signedData, Base64.DEFAULT));
//            Logger.debug("pkcs7.version = " + pkcs7.getVersion());
            Logger.debug("pkcs7.version = " + pkcs7.getCertificates().length);
            Logger.debug("pkcs7.version = " + EncryptHelper.bytesToHexString(pkcs7.getContentInfo().getData()));
//            Logger.debug("pkcs7.version = " + pkcs7.getDigestAlgorithmIds().length);

            X509Certificate prevCert = null; // Previous certificate we've found
            X509Certificate[] certs = pkcs7.getCertificates(); // `java.security.cert.X509Certificate`
            for (int i = 0; i < certs.length; i++) {
                // *** Checking certificate validity period here
                if (prevCert != null) {
                    // Verify previous certificate in chain against this one
                    prevCert.verify(certs[i].getPublicKey());
                }
                prevCert = certs[i];
            }



            SignerInfo[] infos = pkcs7.verify(sha256.getBytes());
            Logger.debug("infos = " + infos.length);
            for (SignerInfo in : infos) {

                Logger.debug("infos = " + in.getCertificate(pkcs7));
                X509Certificate cert = in.getCertificate(pkcs7);
                Logger.debug("cert = " + cert.getSigAlgName());
            }

        } catch (ParsingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }


        return false;
    }



}
